package com.flyxiang.doc.controller;


import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.flyxiang.common.core.utils.file.FileUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件转换
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/convert")
@RequiredArgsConstructor
public class ConvertController {
    //转换文件保存目录
    private static final String convertFilesFloader = "./convertFiles";

    /**
     * word转pdf
     * @param file
     * @param response
     * @throws Exception
     */
    @PostMapping(value = "/wordToPdf")
    public void wordToPdf(@RequestPart("file") MultipartFile file, HttpServletResponse response) throws Exception {

        String fileName = "pdfDemo.pdf";//被下载文件的名称
        response.setContentType("application/pdf");
        FileUtils.setAttachmentResponseHeader(response, fileName);

        try (InputStream inputStream = file.getInputStream();
        OutputStream outputStream = response.getOutputStream()) {
            Document doc = new Document(inputStream);
//            doc.save("T:/test11.pdf", SaveFormat.PDF);
            doc.save(outputStream, SaveFormat.PDF);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("转换完毕==");

    }
}
